<?php
class MemberController extends AdminBaseController {
	/**
	 * 自动执行
	 */
	public function _initialize() {
		parent::_initialize(); 
		$this->db = model('user');
	}

	public function orderadd(){

		if(IS_POST){
			$order_num = intval($_POST['order_num']);
			if($order_num<1)  showmessage('请填写数量');
			$min_num = intval($_POST['min_num']);
			$max_num = intval($_POST['max_num']);
			// 待随机的机器人
			$list = M("user")->field("id,username,is_robot")->where("is_robot")->select();
			// p($list);

			// die;

			$today = model('WalletPrice')->where(array('start'=>date('Y-m-d')))->find();
			$min_price = $today['min_price']*100;
			$max_price = $today['max_price']*100;


			// 次数
			for ($i=0; $i < $order_num; $i++) { 
				$rand_key = array_rand($list);
		        $user = $list[$rand_key];
		        // p($user);
		        $buy_num = mt_rand($min_num,$max_num);
		        $buy_price = mt_rand($min_price,$max_price)/100;

		        // 美元价格
		        $amount = bcmul($buy_num,$buy_price,2);
				// 本次交易的rmb价格
		        $CNY = bcmul($amount,C("site_cny_usd"),2);
		        // 本次交易的手续费
		        $_fee = bcmul($buy_num,(C("site_trate_fee")/100),2);

	            $data = array();
	            $data['order_sn'] = get_order_code("D");
	            // $data['user_id']买家id
	            $data['user_id'] = $user['id'];
	            $data['num'] = $buy_num;
	            $data['cny'] = $CNY;
	            $data['fee'] = $_fee;
	            $data['price'] = $buy_price;
	            $data['amount'] = $amount;
	            $data['type'] = 2;
	            $data['is_robot'] = 1;
	            // 要调取真实数据 
	            $order_count = (int)M("user_trade")->where(array(
	            	"user_id|sell_id"=>array("eq",$user['id']),
	            	"order_status"=>3
	            ))->count();

	            $data['order_num'] = $order_count;
	            // $data['order_appr'] = getUserAppr($user['id']);
	            $data['dateline']  = NOW_TIME;
	            $data['end_time'] = NOW_TIME+C("site_hour")*3600;//交易超时时间 
	            $rut2 = M("user_trade")->add($data);
	            echo M()->getlastsql()."<br>";
	            // die;
	            // if($rut2!==false){
	            // 	session("send_code_time",null);
	            //     showmessage('操作成功！',"",1);
	            // }else{
	            //     showmessage('操作失败');
	            // }

			}


	            if($rut2!==false){
	            	session("send_code_time",null);
	                showmessage('操作成功！',"",1);
	            }else{
	                showmessage('操作失败');
	            }



		}else{
			include $this->admin_tpl('order_add');
		}
	}
	/**
	 * 会员列表
	 */
	public function lists(){
		if(IS_POST){
			//状态 实名认证，注册时间筛选 会员名称
			$sqlmap = array();
			
			// $field = 'id,username,true_name,group_id,mobile_phone,email,user_money,freeze_money,exp,reg_time,user_type,is_renzheng,invite_id,invite_count,invite_all_count,is_ban,is_robot';
			$field  = 'u.id,u.username,u.nickname,u.real_name,u.balance,u.upvaluation,u.freeze_balance,u.if_identification,u.if_complete,u.status,u.register_time,u.freeze_upvaluation,us.username as refer_username';
			//排序
			$_order=isset($_POST['order']) ? ($_POST['order']) : NULL;
			$_sort=isset($_POST['sort']) ? ($_POST['sort']) : NULL;
			if($_order && $_sort){
				$order[$_sort] = $_order;
			}else{
				$order['id'] = 'DESC';
			}
			//状态
			if($_GET['status']){//查询状态
				$sqlmap['status']= $_GET['status'];
			}
			//是否实名认证
			if($_GET['if_identification']){
				$sqlmap['if_identification']= $_GET['if_identification'];
			}
			//是否完善个人信息 
			if($_GET['if_complete']){
				$sqlmap['if_complete']= $_GET['if_complete'];

			}
			//时间查询

			if($_GET["start"]!="" or $_GET["end"]!=""){
				$start = strtotime($_GET['start'].' 00:00:00');
				$end = strtotime($_GET['end'].' 23:59:59');
				$sqlmap['register_time'] =array('between',[date('Y-m-d H:i:s',$start),date('Y-m-d H:i:s',$end)]);
			}

			
			//关键字查询
			// if($_GET['keyword']){
			// 	$sqlmap['username|real_name'] = array('like',"%".trim($_GET['keyword'])."%");
			// }
			



			$search_type = I("refer",1);
			if(isset($_GET['keyword']) && $_GET['keyword']){//分类
				$keyword = $_GET['keyword'];
				

				if($search_type==1){
					$sqlmap['u.username'] = array("LIKE", "%".$keyword."%");
				}
				if($search_type==2){
					$uumap['username'] = array("LIKE", "%".$keyword."%");
					$uu = M("user")->where($uumap)->find();
					$sqlmap['u.refer_id'] = $uu['id'];
				}
				elseif($search_type==3){
					$uumap['username'] = array("LIKE", "%".$keyword."%");
					$uu = M("user")->where($uumap)->find();
					$sqlmap['_string'] = 'FIND_IN_SET('.$uu['id'].',all_head)';
				}
				else{
					$sqlmap['u.username'] = array("LIKE", "%".$keyword."%");
				}

			} 


			//分页
			$pagenum=isset($_GET['page']) ? intval($_GET['page']) : 1;
			$rowsnum=isset($_GET['rows']) && (int)($_GET['rows']) != 0 ? intval($_GET['rows']) : PAGE_SIZE;
			//计算总数 

			$data = array();
			$data['total'] = $this->db->where($sqlmap)->count();
			$data['sql'] = M()->getlastsql();	
			$data['status'] = array(
				array(
					'id'=>1,
					'name'=>"正常"
				),
				array(
					'id'=>2,
					'name'=>"冻结"
				)
			);
			foreach ($data['status'] as $key => $value) {
				if($value['id']==$_GET['status']) $data['status'][$key]['selected'] = true;
			}


			$data['if_identification'] = array(
				array(
					'id'=>1,
					'name'=>"未上传"
				),
				array(
					'id'=>2,
					'name'=>"审核中"
				),
				
				array(
					'id'=>3,
					'name'=>"成功"
				),
				array(
					'id'=>4,
					'name'=>"审核未通过"
				)
			);
			foreach ($data['if_identification'] as $key => $value) {
				if($value['id']==$_GET['if_identification']) $data['if_identification'][$key]['selected'] = true;
			}

			$data['if_complete'] = array(
				array(
					'id'=>1,
					'name'=>'已完善'
				),
				array(
					'id'=>2,
					'name'=>'未完善'
				)
			);
			foreach ($data['if_complete'] as $key => $value) {
				if($value['id']==$_GET['if_complete']) $data['if_complete'][$key]['selected'] = true;
			}



			$data['refer'] = array(
				array(
					'id'=>1,
					'name'=>"会员"
				),
				array(
					'id'=>2,
					'name'=>"直推"
				),
				array(
					'id'=>3,
					'name'=>"团队"
				),				
			);
			foreach ($data['refer'] as $kk => $vv) {
				if($vv['id']==$search_type) $data['refer'][$kk]['selected'] = true;
			}
			$result = M('user u')
						->join('__USER__ us on u.refer_id = us.id')
						->field($field)
						->where($sqlmap)
						->limit(($pagenum-1)*$rowsnum.','.$rowsnum)
						->order($order)
						->select();
			$result = is_array($result) ? $result : array();
			$data['rows'] = $result;

			$data["balance"]= $this->db->where($sqlmap)->sum("balance");
			$data['balance'] = $data['balance'] ? $data['balance'] : 0;
			$data['upvaluation'] = $this->db->where($sqlmap)->sum("upvaluation");
			$data['upvaluation'] = $data['upvaluation'] ? $data['upvaluation'] : 0;
			$data['title']="统计概览-用户数量:".$data["total"]."&nbsp;&nbsp;累计账户余额:".$data['balance']."元,"."&nbsp;&nbsp;累计升值链".$data['upvaluation']."元";
			echo json_encode($data);
		}else{
			include $this->admin_tpl('member_list');
		}
	}

	public function getuser($uid){
		$tmp = M("user")->find($uid);
		return $tmp;
	}
	/**
	 * 会员列表
	 */
	public function user_renzheng(){
		if(IS_POST){
			$sqlmap = array();
			$field = 'id,username,real_name,identidy_number,identity_front,identity_side,status,identification_time,if_identification,balance,freeze_balance,upvaluation,register_time';
			//排序
			$_order=isset($_POST['order']) ? ($_POST['order']) : NULL;
			$_sort=isset($_POST['sort']) ? ($_POST['sort']) : NULL;
			if($_order && $_sort){
				$order[$_sort] = $_order;
			}else{
				$order['id'] = 'DESC';
			}
		
			if(isset($_POST['keyword']) && $_POST['keyword']){//分类
				$keyword = $_POST['keyword'];
				$sqlmap['username|real_name'] = array("LIKE", "%".trim($keyword)."%");
			}
			$sqlmap['if_identification'] = 2;
			//分页
			$pagenum=isset($_GET['page']) ? intval($_GET['page']) : 1;
			$rowsnum=isset($_GET['rows']) && (int)($_GET['rows']) != 0 ? intval($_GET['rows']) : PAGE_SIZE;
			$data['rows'] = M('user')->where($sqlmap)->field($field)->limit(($pagenum-1)*$rowsnum.','.$rowsnum)->order($order)->select();
			//计算总数 
			$data["money"]=$this->db->where($sqlmap)->sum("balance");
			$data['total'] = M('user')->where($sqlmap)->count();
			$data['title']="统计概览-用户数量:".$data["total"]."&nbsp;&nbsp;累计账户余额:".($data["money"]==""?"0.00":$data["money"])."元, ";

			// if (!$data['group']) $data['group']=array();
			if (!$data['rows']) $data['rows']=array();
			// var_dump($data);
			echo json_encode($data);
		}else{
			include $this->admin_tpl('member_user_renzheng_list');
		}
	}

	/**
	 * 认证处理
	 * @return [type] [description]
	 */
	public function setrenzheng(){
		
		$param = I('post.');
		// var_dump($param);
		if($param['if_identification'] == 4){
			$param['identification_remarks'] ?: showmessage('请输入驳回原因');
		}
		$param['identification_time'] = date('Y-m-d H:i:s');
		try{
			M('user')->where(['id'=>$param['user_id']])->save($param);
		}catch(\Exception $e){
			// echo json_encode(['']);
			showmessage($e->getMessage());
		}
		showmessage('操作成功');
	}



	public function dologin(){
		$user_info  = M('user')->where(['username'=>$_GET["username"]])->find();
		session('username',$user_info['username']);
		session('id',$user_info['id']);
		cookie('user_key',authcode('1','ENCODE'));
		$url = "/index.php?m=user&c=trade&a=index";
		// $url="/index.php?m=user&c=api&a=adminlogin&admintype=1&username=".$_GET["username"];
		header("Location:".$url);
	}
	/**
	 * 更新会员
	 */
	public  function update(){
		// p($_POST);
		// die;
		// var_dum(1111);
		$id=$_POST['id'];
		$dialog = TRUE;
		$_POST['birthday']=  strtotime($_POST['birthday']);
		if($id){
			$old_user=M("user")->find($id);
			if($old_user["user_type"]!=$_POST["user_type"]){
				$_POST["admin_update_type"]=1;
			}
			if($this->db->create()){
				$this->db->save();
			}else{
				showmessage($this->db->getError());
			}  
		}else{
			 $_POST['reg_time']=  time();
			if($this->db->create()){
				$id=$this->db->add();
				// 更新联盟人数
				updateInviteAllCount($_POST['invite_str']);
			}else{
			   showmessage($this->db->getError());
			} 
		}
		if($id){
			showmessage('提交成功',U('Member/lists'), 1);
		}else{
			showmessage('提交成功',U('Member/add'), 1); 
		}
	}
	/**
	 * 添加会员
	 */
	public function add(){
		// var_dump(ACTION_NAME);
		$validform = TRUE;
		$dialog = TRUE;
		if(IS_POST){
			
			$param = I('post.');
		
			if(empty($param['username'])) showmessage('手机号不能为空');
			if(!preg_match('/^1([0-9]{9})/',$param['username'])) showmessage('手机号格式不对');
			if(empty($param['refer_id'])) showmessage('推荐人不能为空');
			if(!preg_match('/^1([0-9]{9})/',$param['refer_id'])) showmessage('推荐人手机号格式不对');
			//昵称验证
			$find = M('user')->where(['username'=>$param['username']])->find();
			if($find) showmessage('该手机号已经注册');
			$find = M('user')->where(['username'=>$param['refer_id']])->find();
			if(!$find) showmessage('推荐人不存在，请重新填写');
			$param['refer_id'] = $find['id'];
			$param['salt'] = random(10);
			$param['password'] = $param['pay_password']= md5($param['salt'].substr(trim($param['username']),-6));
			$param['if_admin_add']  = 1;
			
			try{
				$param['register_time'] = date('Y-m-d H:i:s');
				$id = M('user')->add($param);
			
			}catch(\Exception $e){
				showmessage($e->getMessage());
			}

			showmessage('操作成功',U('lists'),1);
		}else{
			// $group = model('UserGroup')->where(array('status'=> 1))->order('sort ASC')->select();
			
			include $this->admin_tpl('member_add');
		}
	} 
	/**
	 * 编辑会员
	 */
	public function edit(){
		// var_dump(1111);
		$validform = TRUE;
		$dialog = TRUE;
		$id = I('id', 0, 'intval');
		if(IS_POST){
			// var_dump(11111);
			$param = I('post.');
			$find = M('user')->where(['username'=>$param['username1']])->find();
			try{
				
				M('user')->where(['username'=>$param['username1']])->save($param);
			}catch(\Exception $e){
				showmessage($e->getMessage());
			}
			showmessage('操作成功',U('lists'),1);
		}else{
			$validform = '';
			$dialog = '';
			$info = $this->db->getById($id);
			// var_dump($info);
			// $agency=M("agency")->select();
			$opt="edit";
			// $region = model('region')->where(array('parent_id' => 1))->select();
			// $city = model('region')->where(array('parent_id' => $info['province']))->select();
			// $district = model('region')->where(array('parent_id' => $info['city']))->select();
			// $group = model('UserGroup')->where(array('status'=> 1))->order('sort ASC')->select();
			if($info['refer_id']>0){
				$yinfo = M("user")->where(['id'=>$info['refer_id']])->field("id,username,nickname")->find();
				// var_dump($yinfo);
			}
			include $this->admin_tpl('member_add');
		}
	} 
	/**
	 * 删除会员
	 */
	public function delete(){
		$id = (array) $_GET['id'];
		if(empty($id)) showmessage('参数错误');
		$sqlmap = $oauth_map = array();
		$sqlmap['id'] = $oauth_map['user_id'] = array("IN", $id);
		$this->db->where($sqlmap)->delete();
		model('user_oauth')->where($oauth_map)->delete();
		showmessage('数据删除成功', U('lists'), 1);
	}
	/**
	 * 重设密码
	 */
	public function repassword(){
		$id=$_GET['id'];
		if(!empty($id)){
			unset($where);
			$where['id']=$id;
			$info=$this->db->where($where)->find();
			$str=substr(trim($info['username']),-6);
			// $data['salt'] = random(10);
			$data['password'] = md5($info['salt'].$str);
			$this->db->where($where)->save($data);
			//邮件通知
			$mail=$info['email'];
			if($mail){
				//读取模板内容
				//$msg_info = M('MsgTemplate')->find(3);
				$title	= $msg_info['title'];
				$content  = $msg_info['content'];				
				//替换模板内容
				//$subject = str_replace(array('{$user_name}','{$password}','{$site_name}'),array($info['username'],'888888',C('site_name')),$content);
			//	$body	= str_replace(array('{$user_name}','{$password}','{$site_name}'),array($info['username'],'888888',C('site_name')),$content);
			//	SendMail($mail,$subject,$body);
			}
			showmessage('会员密码已设为'.$info['username'].'手机号码后六位', U('Member/lists'), 1); 
		}else{
			showmessage('非法操作，请联系管理员！'); 
		}
	}
/**
	 * 重设二级密码
	 */
	public function repinpass(){
		$id=$_GET['id'];
		if(!empty($id)){
			unset($where);
			$where['id']=$id;
			$info=$this->db->where($where)->find();
			$str=substr(trim($info['username']),-6);
			$data['pay_password'] = md5($info['salt'].$str);
			$this->db->where($where)->save($data);
			//邮件通知
			$info=$this->db->where($where)->find();
			$mail=$info['email'];
			if($mail){
				//读取模板内容
				//$msg_info = M('MsgTemplate')->find(3);
				$title	= $msg_info['title'];
				$content  = $msg_info['content'];				
				//替换模板内容
				//$subject = str_replace(array('{$user_name}','{$password}','{$site_name}'),array($info['username'],'888888',C('site_name')),$content);
				//$body	= str_replace(array('{$user_name}','{$password}','{$site_name}'),array($info['username'],'888888',C('site_name')),$content);
				//SendMail($mail,$subject,$body);
			}
			showmessage('会员二级密码已设为'.$info['username'].'手机号码后六位', U('Member/lists'), 1); 
		}else{
			showmessage('非法操作，请联系管理员！'); 
		}
	}
	/**
	 * 余额变动
	 */

	public function set_balance(){
		if(IS_POST){
			$user_money = (float)trim($_GET['balance']);
			if($_GET['at']=='setDec') $user_money = -$user_money;
			$msg = trim($_GET['msg']);
			$user_id = intval($_GET['user_id']);
			if (!$user_money) showmessage('余额必须是不等于零的数字！');
			if (empty($msg)) showmessage('原因必须填写！');
			$money_info=model('user')->find($user_id);
			$data['user_id']=$user_id;
			$data['balance']=$user_money;
			$data['remarks']=$msg;
			$data['add_time']=date('Y-m-d H:i:s');
			$data['type'] = 5;
			//增加记录
			$ret = model('balance_exchange_records')->add($data);
			// echo 1;
			if (!$ret) showmessage('余额变更失败！');
			//改变帐户余额
			$reuslt = $this->db->where(array('id' => $user_id))->setInc('balance',$user_money);
			if (!$reuslt) {
				model('balance_exchange_records')->delete($ret);

				showmessage('余额变更失败！');
			}
			// /* 通知推送 */
			// runhook('n_money_change',array('user_id' => $user_id,'log_id' => $ret));
			showmessage('余额变更成功', U('Member/lists'), 1);
		}else{
			showmessage('非法操作，请联系管理员！');
		}
	}



	public function set_upvaluation(){
		if(IS_POST){
			$user_money = (float)trim($_GET['exp']);
			if($_GET['at']=='setDec') $user_money = -$user_money;
			$msg = trim($_GET['descript']);
			$user_id = intval($_GET['user_id']);
			if (!$user_money) showmessage('GF必须是不等于零的数字！');
			if (empty($msg)) showmessage('原因必须填写！');
			$money_info=model('user')->find($user_id);
			$data['user_id']=$user_id;
			$data['balance']=$user_money;
			$data['remarks']=$msg;
			$data['add_time']=date('Y-m-d H:i:s');
			$data['type'] = 7;
		
			//增加记录
			$ret = model('upvaluation_exchange_records')->add($data);
			// echo 1;
			if (!$ret) showmessage('GF变更失败！');
			//改变帐户余额
			$reuslt = $this->db->where(array('id' => $user_id))->setInc('upvaluation',$user_money);
			if (!$reuslt) {
				model('upvaluation_exchange_records')->delete($ret);

				showmessage('GF变更失败!！');
			}
			// /* 通知推送 */
			// runhook('n_money_change',array('user_id' => $user_id,'log_id' => $ret));
			showmessage('GF变更成功', U('Member/lists'), 1);
		}else{
			showmessage('非法操作，请联系管理员！');
		}
	}
	public function setmoney(){
		if(IS_POST){
			$user_money = (float)trim($_GET['balance']);
			if($_GET['at']=='setDec') $user_money = -$user_money;
			$msg = trim($_GET['msg']);
			$user_id = intval($_GET['user_id']);
			if (!$user_money) showmessage('余额必须是不等于零的数字！');
			if (empty($msg)) showmessage('原因必须填写！');
			$money_info=model('user')->find($user_id);
			$data['user_id']=$user_id;
			$data['money']=$user_money;
			$data['msg']='后台余额变更;原因:'.$msg;
			$data['dateline']=NOW_TIME;
			$data['type'] = 1;
			$data['user_money'] = $money_info["user_money"]+$user_money;
			$data['freeze_money'] = $money_info["freeze_money"];
			//增加记录
			$ret = model('user_moneylog')->add($data);
			// echo 1;
			if (!$ret) showmessage('余额变更失败！');
			//改变帐户余额
			$reuslt = $this->db->where(array('id' => $user_id))->setInc('user_money',$user_money);
			if (!$reuslt) {
				model('user_moneylog')->delete($ret);
				echo 2;
				showmessage('余额变更失败！');
			}
			/* 通知推送 */
			runhook('n_money_change',array('user_id' => $user_id,'log_id' => $ret));
			showmessage('余额变更成功', U('Member/lists'), 1);
		}else{
			showmessage('非法操作，请联系管理员！');
		}
	}
	/**
	 * 积分变动
	 */
	public function setpoints(){
		if($_POST){
			$pay_points=I('exp',0,'intval');
			if($_POST['at']=='setDec') $pay_points=-$pay_points;
			$descript=$_POST['descript'];
			$user_id=intval($_POST['user_id']);
			if ((int)$_POST['exp']==0) showmessage('积分必须是整数！');
			if (empty($descript)) showmessage('原因必须填写！');  
			$data['user_id']=$user_id;
			$points_info=model('user')->find($user_id);
			$data['descript']=$descript;
			$data['type']=1;
			$data['user_points']=$points_info["pay_points"]+$pay_points;
			$data['pay_points']=$pay_points;
			$data['time']=TIME();
			//增加记录
			$points=model('User_pointslog');
			$points->add($data);
			//改变帐户积分
			unset ($where);
			unset ($data);
			$where['id']=$user_id;
			$data['pay_points']=array('exp','pay_points + '.$pay_points);
			$this->db->where($where)->save($data);
			showmessage('积分变动成功', U('Member/lists'), 1);	 
		}else{
			showmessage('非法操作，请联系管理员！'); 
		}
	}   
	/**
	 * 经验变动
	 */
	public function setexp(){
		if($_POST){
			$expval=I('exp',0,'intval');
			$at = $_GET['at'];
			$user_id = $_GET['user_id'];
			if ($expval==0) showmessage('经验必须是整数！');
			if ($at == 'setDec') $expval = 0-$expval;
			action_exp($user_id,$expval);
			showmessage('经验变动成功', U('Member/lists'), 1);	 
		}else{
			showmessage('非法操作，请联系管理员！'); 
		}
	} 


	//实名认证
	public function renzhegn_check(){
		$id = $_GET['id'];
		$result = M('user')->where(['id'=>$id])->setField('if_complete');

	}
}